﻿using SchoolCommunicationSystem.Models;
using SCS.Business;
using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web.Security;
namespace SchoolCommunicationSystem.Controllers
{
    public class MembersController : Controller
    {
        //
        // GET: /Members/
        MembershipService _membershipServices = new MembershipService();     

        /// <summary>
        /// LogIn
        /// </summary>
        /// <returns>View</returns>
        public ActionResult LogIn()
        {
            // Create the empty view model
            var viewModel = new LogOnViewModel();
            //   _membershipServices.TestCreatUser();
            // See if a return url is present or not and add it
            var returnUrl = Request["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                viewModel.ReturnUrl = returnUrl;
            }

            return View(viewModel);
        }

        /// <summary>
        /// Log in post
        /// </summary>
        /// <param name="model">LogOnViewModel</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult LogIn(LogOnViewModel model)
        {
            var username = model.UserName;
            var password = model.Password;

            try
            {
                if (ModelState.IsValid)
                {
                    if (_membershipServices.ValidateUser(username, password, System.Web.Security.Membership.MaxInvalidPasswordAttempts))
                    {
                        // Set last login date
                        var user = _membershipServices.GetUser(username);
                        if (!user.isLockedOut)
                        {
                            FormsAuthentication.SetAuthCookie(username, model.RememberMe);
                            // We use temp data because we are doing a redirect
                            /*           TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                       {
                                           Message = LocalizationService.GetResourceString("Members.NowLoggedIn"),
                                           MessageType = GenericMessages.success
                                       };*/
                            if (user.MembershipRoles.FirstOrDefault().roleID == 1)
                            {
                                return RedirectToAction("Index", "Home", new { area = string.Empty });
                            }
                            else if (user.MembershipRoles.FirstOrDefault().roleID == 3
                                  || user.MembershipRoles.FirstOrDefault().roleID == 4)
                            {
                                return RedirectToAction("Index", "Home", new { area = string.Empty });
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home", new { area = string.Empty });
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);

        }

        /// <summary>
        /// LogOut
        /// </summary>
        /// <returns>RedirectToAction("Login", "Members")</returns>
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Login", "Members");

        }

        /// <summary>
        /// ChangePassword
        /// </summary>
        /// <returns>View</returns>
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        /// <summary>
        /// ChangePassword
        /// </summary>
        /// <param name="model">ChangePasswordViewModel</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            var changePasswordSucceeded = true;
            var UserTochange = _membershipServices.GetUser(User.Identity.Name);
            if (ModelState.IsValid)
            {
                try
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    changePasswordSucceeded = _membershipServices.ChangePassword(UserTochange, model.OldPassword, model.NewPassword);
                }
                catch (Exception ex)
                {
                    changePasswordSucceeded = false;
                }
            }

            if (!changePasswordSucceeded)
            {
                ModelState.AddModelError("", "[Mật khẩu hiện tại] không đúng");
                return View(model);
            }
            return View();
        }

        /// <summary>
        /// ForgotPassword
        /// </summary>
        /// <returns>View</returns>
        public ActionResult ForgotPassword()
        {
            return View();
        }
        /// <summary>
        /// ForgotPassword
        /// </summary>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult ForgotPassword(ForgotPassWordViewModel model)
        {
            string error = "ABCBB";
            string newPassword = string.Empty;
            if (_membershipServices.ResetPassword(model.UserName, model.Phone, out error, out newPassword))
            {
                Random random = new Random();
                TempData["Msg"] = error;
                string userapi = "fuscscom";
                string passwordapi = "aguda5uN";
                string smsCode = random.Next(100000000, 999999999).ToString();
                string smsContent = "Mat khau moi cua ban tai he thong so lien lac dien tu SCS la: " + newPassword;
                string api = "http://netvn.vn/apis/send_sms?smsUser={0}&smsPass={1}&smsNumber={2}&smsContent={3}&smsCode={4}";
                string ouput = string.Format(api, userapi, passwordapi, model.Phone, smsContent, smsCode); 
                WebRequest myWebRequest = WebRequest.Create(ouput);
                WebResponse myWebResponse = myWebRequest.GetResponse();
                var a = myWebResponse.ResponseUri;
                myWebResponse.Close();
            }
            else
            {
                TempData["Msg"] = error;
            }
            return View();
        }
        /// <summary>
        /// Change Information
        /// </summary>
        /// <returns>View</returns>
        [Authorize]
        public ActionResult ChangeInformation()
        {
            UserProfilesViewModel userProfiles = new UserProfilesViewModel();
            var loginUser= _membershipServices.GetUser(User.Identity.Name);
            if (loginUser.Parents.Count > 0)
            {
                userProfiles.Parents = loginUser.Parents.FirstOrDefault();
            }
            if (loginUser.Teachers.Count > 0)
            {
                userProfiles.Teacher = loginUser.Teachers.FirstOrDefault();
            }

            userProfiles.MembershipUser = loginUser;
            return View(userProfiles);
        }
        [Authorize]
        [HttpPost]
        public ActionResult ChangeInformation(UserProfilesViewModel model)
        {
            if (ModelState.IsValid)
            {
                var loginUser = _membershipServices.GetUser(User.Identity.Name);
                loginUser.email = model.MembershipUser.email;
                _membershipServices.Save(loginUser);
                if (model.Parents != null)
                {

                }
                if (model.Teacher != null)
                {

                }

                //   userProfiles.MembershipUser = loginUser;
                return View(model);
            }
            return RedirectToAction("Index","Home");
        }
        /*
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ForgotPassword()//ForgotPasswordViewModel forgotPasswordViewModel)
        {
            var changePasswordSucceeded = true;
            var currentUser = _membershipServices.CreateEmptyUser();
            var newPassword = StringUtils.RandomString(8);


            if (ModelState.IsValid)
            {
                try
                {
                    // currentUser = MembershipService.GetUserByEmail(forgotPasswordViewModel.EmailAddress);
                    changePasswordSucceeded = _membershipServices.ResetPassword(currentUser, newPassword);
                }

                catch (Exception ex)
                {
                    //   unitOfWork.Rollback();
                    //  LoggingService.Error(ex);
                    changePasswordSucceeded = false;
                }
            }
            return View();
        }

        /*    // Success send newpassword to the user telling them password has been changed
            using (UnitOfWorkManager.NewUnitOfWork())
            {
                var sb = new StringBuilder();
                sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("Members.ForgotPassword.Email"), SettingsService.GetSettings().ForumName));
                sb.AppendFormat("<p><b>{0}</b></p>", newPassword);
                var email = new Email
                {
                    EmailFrom = SettingsService.GetSettings().NotificationReplyEmail,
                    EmailTo = currentUser.Email,
                    NameTo = currentUser.UserName,
                    Subject = LocalizationService.GetResourceString("Members.ForgotPassword.Subject")
                };
                email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                _emailService.SendMail(email);

                if (changePasswordSucceeded)
                {
                    // We use temp data because we are doing a redirect
                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message = LocalizationService.GetResourceString("Members.ForgotPassword.SuccessMessage"),
                        MessageType = GenericMessages.success
                    };
                    return View();
                }

                ModelState.AddModelError("", LocalizationService.GetResourceString("Members.ForgotPassword.ErrorMessage"));
                return View(forgotPasswordViewModel);
            }
        }

        */
    }
}
